//
//  YXLProduceListViewController.m
//  MyNewProject
//
//  Created by 于兴雷 on 2019/2/16.
//  Copyright © 2019年 sun. All rights reserved.
//

#import "YXLProduceListViewController.h"
#import "XMHistoryCollectionViewCell.h"
#import "XRWaterfallLayout.h"
#import "ProductDetailViewController.h"

#import "OYCountDownManager.h"
@interface YXLProduceListViewController ()<UICollectionViewDataSource,XRWaterfallLayoutDelegate,UICollectionViewDelegate>{
    NSMutableArray  * modelArray;
    BOOL isFirstLoad;
}


@property (nonatomic, strong) NSMutableDictionary * dataDictionary;//存储各类数据数组
@property (nonatomic, strong) NSArray *keyArray;

@property (nonatomic, assign) BOOL canScroll;
@property (nonatomic, assign) int page;
@property (nonatomic, strong) NSNumber * class_id;
@property (nonatomic , retain)UITableView *tableView;

@end

static NSString *const superCollectionViewCellID = @"XMHistoryCollectionViewCell";

@implementation YXLProduceListViewController
-(NSMutableDictionary *)dataDictionary{
    if (!_dataDictionary) {
        _dataDictionary = [[NSMutableDictionary alloc]initWithDictionary:@{@"MainNewProductType":@[],@"MainHotProductType":@[],@"MainPurchaseProductType":@[],@"MainHistoryProductType":@[],@"MallLifeProductType":@[],@"MallBedProductType":@[],@"MallLimitProductType":@[],@"MallLikeProductType":@[]}];
    }
    return _dataDictionary;
}
-(NSArray *)keyArray{
    if (!_keyArray) {
        _keyArray = @[@"MainNewProductType",@"MainHotProductType",@"MainPurchaseProductType",@"MainHistoryProductType",@"MallLifeProductType",@"MallBedProductType",@"MallLimitProductType",@"MallLikeProductType"];
    }
    return _keyArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.page = 1;
    self.class_id = @(0);
    [self initNotification];
    [self initView];
    isFirstLoad = YES;
    [self getData];
}

-(void)initNotification
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(someMethod)
                                                     name:UIApplicationDidBecomeActiveNotification object:nil];
    });

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headRefresh:) name:@"homePageHeadRefresh" object:nil];
    
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headRefresh:) name:@"mallPageHeadRefresh" object:nil];

}
-(void)shuaXinData:(NSNotification *)notification
{

    NSDictionary * infoDic = [notification object];
    self.class_id = infoDic[@"ItemAtIndexPath"];


    [self getData];
}
-(void)someMethod
{
    self.page = 1;
    [self getData];
//    [self.collectionView reloadData];
}
-(void)initView
{
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
    lineView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:lineView];
    
    [self.view addSubview:self.collectionView];
}

- (UICollectionView *)collectionView {
    if (_collectionView == nil) {
        //创建瀑布流布局
        XRWaterfallLayout *waterfall = [XRWaterfallLayout waterFallLayoutWithColumnCount:2];
        //或者一次性设置
        [waterfall setColumnSpacing:10 rowSpacing:10 sectionInset:UIEdgeInsetsMake(10, 10, 10, 10)];
        //设置代理，实现代理方法
        waterfall.delegate = self;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREENH_HEIGHT-SKTabBar_Height-SKStatusBar_Height -40 - self.topHeight) collectionViewLayout:waterfall];
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.alwaysBounceVertical = YES;

        [_collectionView registerClass:[XMHistoryCollectionViewCell class] forCellWithReuseIdentifier:superCollectionViewCellID];
        if (@available(iOS 11.0, *)) {
            _collectionView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        SKWeakSelf;
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.page = 1;
            [weakSelf getData];

                }];
        _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{

            weakSelf.page ++;

            [weakSelf getData];
            
        }];
        
    }
    return _collectionView;
}
#pragma -mark XRWaterfallLayoutDelegate
//根据item的宽度与indexPath计算每一个item的高度
- (CGFloat)waterfallLayout:(XRWaterfallLayout *)waterfallLayout itemHeightForWidth:(CGFloat)itemWidth atIndexPath:(NSIndexPath *)indexPath {
    //根据数据 展示不同的高度
    return itemWidth + 80;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSString * dataKey = self.keyArray[self.dataType];
    NSMutableArray * dataArray = [NSMutableArray arrayWithArray:self.dataDictionary[dataKey]];
    return dataArray.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString * dataKey = self.keyArray[self.dataType];
    NSMutableArray * dataArray = [NSMutableArray arrayWithArray:self.dataDictionary[dataKey]];
    XMHistoryCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:superCollectionViewCellID forIndexPath:indexPath];
    cell.indexPath = indexPath;
    XM_AuctionProductModel * model = (XM_AuctionProductModel *)dataArray[indexPath.row];
    [cell LoadProductInfomation:dataArray[indexPath.row] isShop:self.dataType > 3];
    if (self.dataType > 3 || model.status > 4) {// > 4是积分
        cell.countDownTimelab.hidden = YES;
        cell.timeLabel.hidden = YES;
    }
    SKWeakSelf;
    cell.countDownZero = ^(XM_AuctionProductModel * model) {
        [weakSelf getData];
    };
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSString * dataKey = self.keyArray[self.dataType];
    NSMutableArray * dataArray = [NSMutableArray arrayWithArray:self.dataDictionary[dataKey]];
    XM_AuctionProductModel * pModel = dataArray[indexPath.row];
    ProductDetailViewController * pdVC = [[ProductDetailViewController alloc]init];
    
    if (self.dataType > 3) {//商城
        pdVC.type = 5;//1未开始2进行中3已结束4已成交5积分
    }else{
        pdVC.type = pModel.status;//1未开始2进行中3已结束4已成交5积分
    }
    pdVC.productId = pModel.productId;
    [self.navigationController pushViewController:pdVC animated:YES];
}

#pragma mark 倒计时方法
- (void)dealloc {
    // 废除定时器
    [kCountDownManager invalidate];
    // 清空时间差
    [kCountDownManager reload];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)getData
{
   NSDictionary *paramDic = @{};
    
    switch (self.dataType) {
        case MainNewProductType:
            paramDic = @{@"type":@(1),@"page":@(self.page),@"class_id":self.class_id};
            break;
        case MainHotProductType:
            paramDic = @{@"type":@(2),@"status":@(2),@"page":@(self.page),@"class_id":self.class_id};
            break;
        case MainPurchaseProductType:
            paramDic = @{@"type":@(2),@"status":@(1),@"page":@(self.page),@"class_id":self.class_id};
            break;
        case MainHistoryProductType:
            paramDic = @{@"type":@(2),@"status":@(3),@"page":@(self.page),@"class_id":self.class_id};
            break;
        case MallLifeProductType:
            paramDic = @{@"type":@(1),@"page":@(self.page),@"class_id":self.class_id};
            break;
        case MallBedProductType:
            paramDic = @{@"type":@(2),@"page":@(self.page),@"class_id":self.class_id};
            break;
        case MallLimitProductType:
            paramDic = @{@"type":@(3),@"page":@(self.page),@"class_id":self.class_id};
            break;
        case MallLikeProductType:
            paramDic = @{@"type":@(4),@"page":@(self.page),@"class_id":self.class_id};
            break;
            
        default:
            break;
    }
    
    NSString *urlStr = @"Jifen/getJifenList";
    
    if (self.topHeight == 0) {
        urlStr = @"Index/getSellList";

        switch (self.dataType) {
            case MainNewProductType:
                paramDic = @{@"type":@(1),@"page":@(self.page)};
                break;
            case MainHotProductType:
                paramDic = @{@"type":@(2),@"status":@(2),@"page":@(self.page)};
                break;
            case MainPurchaseProductType:
                paramDic = @{@"type":@(2),@"status":@(1),@"page":@(self.page)};
                break;
            case MainHistoryProductType:
                paramDic = @{@"type":@(2),@"status":@(3),@"page":@(self.page)};
                break;
            case MallLifeProductType:
                paramDic = @{@"type":@(1),@"page":@(self.page)};
                break;
            case MallBedProductType:
                paramDic = @{@"type":@(2),@"page":@(self.page)};
                break;
            case MallLimitProductType:
                paramDic = @{@"type":@(3),@"page":@(self.page)};
                break;
            case MallLikeProductType:
                paramDic = @{@"type":@(4),@"page":@(self.page)};
                break;

            default:
                break;
        }
    }

    [YQNetworking postWithUrl:urlStr refreshRequest:YES cache:NO params:paramDic progressBlock:nil successBlock:^(id response) {
        NSMutableArray * dataArr = [NSMutableArray arrayWithArray:response[@"data"]];//请求得到的数据
        NSString * dataKey = self.keyArray[self.dataType];
        NSMutableArray * dataArray;
        if (self.page > 1) {//加载 
            dataArray = [NSMutableArray arrayWithArray:(NSArray *)self.dataDictionary[dataKey]];//原有数据
        }else{
            dataArray = [NSMutableArray arrayWithArray:@[]];//刷新
            [self.dataDictionary setObject:dataArray forKey:dataKey];

        }
       
        if ([dataArr count]>0) {
            for (NSDictionary * dic in dataArr) {
                XM_AuctionProductModel * pModel =  [XM_AuctionProductModel modelWithDictionary:dic];
                pModel.typeName = dataKey;
                if (pModel.status == 5) {
                    pModel.status = 3;
                }
                [dataArray addObject:pModel];
            }
            [self.dataDictionary setObject:dataArray forKey:dataKey];

            if (self->isFirstLoad) {//首次加载
                // 启动倒计时管理
                [kCountDownManager start];
            }else{
                [kCountDownManager reload];
            }
//            [self.collectionView reloadData];
        }
        [self.collectionView reloadData];

        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
        self->isFirstLoad = NO;
    } failBlock:^(NSError *error) {
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView.mj_footer endRefreshing];
    }];
}

-(void)headRefresh:(NSNotification *)nofi
{
    NSDictionary *paramDic = nofi.object;
    
    self.tableView = paramDic[@"tableView"];
    
    self.page = 1;
    [self getData];

//
//    NSLog(@"headRefreshparamDic ==== %@",paramDic);
}
//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    
//    CGFloat contentOffsetY = scrollView.contentOffset.y;
//    
//    if (contentOffsetY<=0) {
//        
//        self.collectionView.userInteractionEnabled = YES;
//
//        self.collectionView.scrollEnabled  = YES;
//        
//    }
//    else
//    {
//        if ([CommonToolHelper shareInstance].currentHeiht >=181) {
//            self.collectionView.scrollEnabled  = YES;
//            self.collectionView.userInteractionEnabled = YES;
//
//        }
//        else
//        {
//            self.collectionView.scrollEnabled  = NO;
//            self.collectionView.userInteractionEnabled = NO;
//
//        }
//    }
//    
//    
//}
//-(void)footRefresh:(NSNotification *)nofi
//{
//    NSDictionary *paramDic = nofi.object;
//    NSLog(@"footRefreshparamDic ==== %@",paramDic);
//}

@end
